/* eslint-disable */
import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Table, Modal, message, Select } from 'antd';
import axios from 'axios';
import './patriarch.css';
import { getUser, createUser, updateUser, deleteUser, searchUsers } from '../../api/PatriachIndex';

const Patriarch = () => {
  const [listData, setListData] = useState([]);
  const [TableData, setTableData] = useState([]);
  const [modalType, setModalType] = useState(0); // 0为新增，1为编辑
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [students, setStudents] = useState([]);
  const { Option } = Select;
  const [studentOptions, setStudentOptions] = useState([]);
  const [selectedStudent, setSelectedStudent] = useState(null);

  let clickCount = 0;
  let lastClickTime = null;
  let isBlocked = false;
  let blockTimer = null;

  // 新增/编辑
  const handClick = (type, rowData) => {
    setIsModalOpen(!isModalOpen);
    if (type === 'add') {
      setModalType(0);
      form.resetFields();
    } else {
      setModalType(1);
      const cloneData = JSON.parse(JSON.stringify(rowData));
      form.setFieldsValue({
        ...cloneData,
        student_id: cloneData.student_id,
        studentNumber: cloneData.studentNumber,
        name: cloneData.studentName
      });
    }
  };

  // 提交-搜索
  const handFinish = async (values) => {
    const currentTime = Date.now();

    if (lastClickTime && currentTime - lastClickTime > 60000) {
      clickCount = 0;
      lastClickTime = null;
      isBlocked = false;
      clearTimeout(blockTimer);
    }

    if (isBlocked) return;

    clickCount++;
    lastClickTime = currentTime;

    if (clickCount > 3) {
      message.error("点击次数过多，请一分钟后再试。");
      isBlocked = true;
      blockTimer = setTimeout(() => {
        isBlocked = false;
        clickCount = 0;
      }, 60000);
      return;
    }

    const keyword = values.keyword?.trim();
    setSearchKeyword(keyword);

    if (!keyword) {
      getTableData();
      return;
    }

    try {
      const res = await searchUsers({ keyword });

      // 获取所有学生信息
      const studentResponse = await axios.get('http://47.111.104.30:8080/api/v2/students', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      });
      const students = studentResponse.data;

      // 将学生学号和姓名添加到家长信息中
      const updatedFamilyMessages = res.data.map(familyMessage => {
        const student = students.find(student => student.id === familyMessage.student_id);
        return {
          ...familyMessage,
          studentNumber: student ? student.number : '',
          studentName: student ? student.name : ''
        };
      });

      setTableData(updatedFamilyMessages);
    } catch (error) {
      console.error("搜索失败:", error);
      message.error(`搜索失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 删除
  const handDelete = async (rowData) => {
    setCurrentRow(rowData);
    setIsDeleteModalOpen(true);
  };

  // 确认删除
  const handleDeleteConfirm = async () => {
    try {
      await deleteUser(currentRow.id);
      if (searchKeyword) {
        const res = await searchUsers({ keyword: searchKeyword });
        setTableData(res.data);
      } else {
        getTableData();
      }
      setIsDeleteModalOpen(false);
      message.success("删除成功");
    } catch (error) {
      console.error("删除失败:", error);
      message.error(`删除失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 取消删除
  const handleDeleteCancel = () => {
    setIsDeleteModalOpen(false);
  };


  // 获取用户列表数据
  const getTableData = async (params = {}) => {
    try {
      const res = await getUser(params);
      const familyMessages = res.data;

      // 获取所有学生信息
      const studentResponse = await axios.get('http://47.111.104.30:8080/api/v2/students', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      });
      const students = studentResponse.data;

      // 将学生学号和姓名添加到家长信息中
      const updatedFamilyMessages = familyMessages.map(familyMessage => {
        const student = students.find(student => student.id === familyMessage.student_id);
        return {
          ...familyMessage,
          studentNumber: student ? student.number : '',
          studentName: student ? student.name : ''
        };
      });

      setTableData(updatedFamilyMessages); // 使用 setTableData 更新表格数据
    } catch (error) {
      console.error("获取用户数据失败:", error);
      message.error(`获取用户数据失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 添加搜索学生的方法
  const handleStudentSearch = async (value) => {
    if (value) {
      try {
        const response = await axios.get(`http://47.111.104.30:8080/api/v2/students/search?keyword=${value}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        });
        setStudentOptions(response.data.map(student => ({
          value: student.id,
          label: `${student.name} (${student.number})`
        })));
      } catch (error) {
        console.error('搜索学生失败:', error);
      }
    }
  };

  const handleStudentSelect = (value) => {
    const student = studentOptions.find(option => option.value === value);
    setSelectedStudent(student);
    form.setFieldsValue({
      student_id: student.value,
      studentNumber: student.label.split(' ')[1].replace('(', '').replace(')', ''),
      name: student.label.split(' ')[0]
    });
  };

  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('http://47.111.104.30:8080/api/v2/students', {
          headers: {
            Authorization: `Bearer ${token}`
          }
        });
        setStudents(response.data);
      } catch (error) {
        console.error('获取学生列表失败:', error);
      }
    };
    fetchStudents();
    getTableData(); // 添加这行代码以在组件加载时获取表单数据
  }, []);

  // 弹窗确定
  const handleOk = async () => {
    const currentTime = Date.now();

    if (lastClickTime && currentTime - lastClickTime > 60000) {
      clickCount = 0;
      lastClickTime = null;
      isBlocked = false;
      clearTimeout(blockTimer);
    }

    if (isBlocked) return;

    clickCount++;
    lastClickTime = currentTime;

    if (clickCount > 3) {
      message.error("点击次数过多，请一分钟后再试。");
      isBlocked = true;
      blockTimer = setTimeout(() => {
        isBlocked = false;
        clickCount = 0;
      }, 60000);
      return;
    }

    try {
      const val = await form.validateFields();
      const requestPromise = modalType ? updateUser(val) : createUser(val);
      await requestPromise;

      if (searchKeyword) {
        const res = await searchUsers({ keyword: searchKeyword });
        setTableData(res.data);
      } else {
        getTableData();
      }

      setIsModalOpen(false);
      message.success(modalType ? "更新成功" : "新增成功");
    } catch (error) {
      console.error("操作失败:", error);
      message.error(`操作失败: ${error.response?.data?.message || error.message}`);
    }
  };

  // 弹窗取消
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  // 列配置
  const columns = [
    {
      title: '学生姓名',
      dataIndex: 'studentName',
    },
    {
      title: '学生学号',
      dataIndex: 'studentNumber',
    },
    {
      title: '父亲姓名',
      dataIndex: 'fatherName',
    },
    {
      title: '母亲姓名',
      dataIndex: 'motherName',
    },
    {
      title: '父亲联系方式',
      dataIndex: 'fatherPhone',
    },
    {
      title: '母亲联系方式',
      dataIndex: 'motherPhone',
    },
    {
      title: '家庭住址',
      dataIndex: 'homeAddress',
    },
    {
      title: '操作',
      render: (rowData) => {
        return (
          <div className='flex-box'>
            <Button style={{ marginRight: '5px' }} onClick={() => { handClick('edit', rowData) }}>编辑</Button>
            <Button type='primary' danger onClick={() => { handDelete(rowData) }}>删除</Button>
          </div>
        );
      }
    },
  ];

  return (
    <div className='patriarch' >
      <div className='flex-box space-between'>
        <Form
          layout='inline'
          onFinish={handFinish}
          form={searchForm}
          onValuesChange={(changedValues, allValues) => {
            if (!changedValues.keyword) {
              getTableData();
            }
          }}
        >
          <Form.Item name='keyword'>
            <Input placeholder='请输入关键词' style={{ height: '40px' }} />
          </Form.Item>
          <Form.Item>
            <Button type='primary' htmlType='submit' style={{ height: '40px' }}>搜索</Button>
          </Form.Item>
        </Form>
        <Button type='primary' onClick={() => { handClick('add') }}>新增</Button>
      </div>
      <Table
        style={{ marginTop: '10px' }}
        columns={columns}
        dataSource={TableData}
        rowKey={'id'}
        pagination={{ pageSize: 10 }}
      />
      <Modal
        open={isModalOpen}
        title={modalType ? '编辑信息' : '新增信息'}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 14 }}
          labelAlign='left'
        >
          {modalType === 1 && (
            <Form.Item
              label="学生ID"
              name="id"
              rules={[
                {
                  required: true,
                  message: '请输入学生ID'
                }
              ]}
            >
              <Input disabled placeholder='学生ID' />
            </Form.Item>
          )}
          <Form.Item
            label="学生"
            name="student_id"
            rules={[
              {
                required: true,
                message: '请选择学生'
              }
            ]}
          >
            <Select
              showSearch
              placeholder="请输入学生姓名或学号搜索"
              filterOption={false}
              onSearch={handleStudentSearch}
              onSelect={handleStudentSelect}
              options={studentOptions}
            />
          </Form.Item>
          <Form.Item
            label="学生学号"
            name="studentNumber"
            rules={[
              {
                required: true,
                message: '请输入学生学号'
              }
            ]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="学生姓名"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入学生姓名'
              },
              {
                max: 20,
                message: '学生姓名不能超过20个字符'
              }
            ]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="父亲姓名"
            name="fatherName"
            rules={[
              {
                max: 20,
                message: '父亲姓名不能超过20个字符'
              }
            ]}
          >
            <Input placeholder='请输入父亲姓名' maxLength={20} />
          </Form.Item>
          <Form.Item
            label="母亲姓名"
            name="motherName"
            rules={[
              {
                max: 20,
                message: '母亲姓名不能超过20个字符'
              }
            ]}
          >
            <Input placeholder='请输入母亲姓名' maxLength={20} />
          </Form.Item>
          <Form.Item
            label="父亲联系方式"
            name="fatherPhone"
            rules={[
              {
                validator: (_, value) => {
                  if (!value) {
                    return Promise.resolve();
                  }
                  if (isNaN(value)) {
                    return Promise.reject('父亲联系方式必须为数字！');
                  }
                  if (value.length !== 11) {
                    return Promise.reject('父亲联系方式必须为11位！');
                  }
                  return Promise.resolve();
                }
              }
            ]}
          >
            <Input placeholder='请输入父亲联系方式' maxLength={11} />
          </Form.Item>
          <Form.Item
            label="母亲联系方式"
            name="motherPhone"
            rules={[
              {
                validator: (_, value) => {
                  if (!value) {
                    return Promise.resolve();
                  }
                  if (isNaN(value)) {
                    return Promise.reject('母亲联系方式必须为数字！');
                  }
                  if (value.length !== 11) {
                    return Promise.reject('母亲联系方式必须为11位！');
                  }
                  return Promise.resolve();
                }
              }
            ]}
          >
            <Input placeholder='请输入母亲联系方式' maxLength={11} />
          </Form.Item>
          <Form.Item
            label="家庭住址"
            name="homeAddress"
            rules={[
              {
                required: true,
                message: '请输入家庭住址'
              },
              {
                max: 20,
                message: '家庭住址不能超过20个字符'
              }
            ]}
          >
            <Input placeholder='请输入家庭住址' maxLength={20} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        open={isDeleteModalOpen}
        title="确认删除"
        onOk={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        okText="确认"
        cancelText="取消"
      >
        <p>确认删除该信息吗？</p>
      </Modal>
    </div>
  );
};

export default Patriarch;